﻿using System;
using Sandbox.Common.ObjectBuilders;
using Sandbox.Game;
using Sandbox.Game.Entities;
using Sandbox.Game.Entities.Character.Components;
using Sandbox.ModAPI;
using VRage.Game.Components;
using VRage.Game.Entity;
using VRage.Game.ModAPI;
using VRage.ModAPI;
using VRage.ObjectBuilders;

namespace Vicizlat.MultifloorCargoElevator
{
    [MyEntityComponentDescriptor(typeof(MyObjectBuilder_AdvancedDoor), false, new string[] { "VCZ_Cargo_Elevator_Floor", "VCZ_Cargo_Elevator_Floor_Half" })]
    public class MultifloorCargoElevatorFloors : MyGameLogicComponent
    {
        private IMyAdvancedDoor ElevatorFloor;
        private IMyExtendedPistonBase Elevator_block;

        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;
            ElevatorFloor = (IMyAdvancedDoor)Entity;
        }

        public override void Close() => NeedsUpdate = MyEntityUpdateEnum.NONE;

        public override void UpdateBeforeSimulation()
        {
            try
            {
                if (MyAPIGateway.Utilities.IsDedicated) return;
                if (ElevatorFloor.CubeGrid.Physics == null || !ElevatorFloor.IsFunctional) return;
                if (MyAPIGateway.Gui.ActiveGamePlayScreen != null) return;
                if (MyAPIGateway.Session.Player.Character == null) return;

                if (Elevator_block == null && ElevatorFloor.CustomData.Contains("Parent Elevator ID"))
                {
                    MyEntity Entity;
                    MyEntities.TryGetEntityById(GetElevatorID("Parent Elevator ID"), out Entity);
                    if ((Entity as IMyEntity) is IMyCubeBlock) Elevator_block = Entity as IMyExtendedPistonBase;
                }
                if (Elevator_block == null || Elevator_block.Closed || !Elevator_block.IsFunctional) return;
                if (ElevatorFloor.HasLocalPlayerAccess() && ElevatorFloor.OpenRatio == 0)
                {
                    IMyCharacter Player = MyAPIGateway.Session.Player.Character;
                    if (Player.Components.Get<MyCharacterDetectorComponent>()?.UseObject != null)
                    {
                        if (Player.Components.Get<MyCharacterDetectorComponent>().DetectedEntity != ElevatorFloor) return;
                        bool UseDummy = MyAPIGateway.Input.IsGameControlReleased(MyControlsSpace.USE) || MyAPIGateway.Input.IsGameControlReleased(MyControlsSpace.PRIMARY_TOOL_ACTION);
                        if (UseDummy) Elevator_block.GameLogic.GetAs<MultifloorCargoElevator>().SendToFloor(GetFloor("Floor No."));
                    }
                }
            }
            catch (Exception e)
            {
                Logging.Instance.WriteLine("[ Error in 'MultifloorCargoElevatorFloors': " + e.StackTrace + " ]");
            }
        }

        private long GetElevatorID(string Name)
        {
            int ValuePosition = ElevatorFloor.CustomData.IndexOf("[", ElevatorFloor.CustomData.IndexOf(Name)) + 1;
            int ValueLenght = ElevatorFloor.CustomData.IndexOf("]", ElevatorFloor.CustomData.IndexOf(Name)) - ValuePosition;
            return Int64.Parse(ElevatorFloor.CustomData.Substring(ValuePosition, ValueLenght));
        }

        private int GetFloor(string Name)
        {
            int ValuePosition = ElevatorFloor.CustomData.IndexOf("[", ElevatorFloor.CustomData.IndexOf(Name)) + 1;
            return Int32.Parse(ElevatorFloor.CustomData.Substring(ValuePosition, 1));
        }
    }
}